import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'

/**
 * 通用语音输入功能
 * 支持通过语音输入，返回识别文本，可用于各种场景（待办、聊天等）
 */
export function useVoiceInput(options = {}) {
  const {
    onTranscript = null, // 识别文本回调 (transcript, isFinal)
    onRecordingStart = null,
    onRecordingStop = null,
    lang = 'zh-CN', // 识别语言
    continuous = true, // 持续监听
    autoStop = false // 是否在识别完成后自动停止
  } = options

  // 语音识别相关状态
  const isVoiceSupported = ref(false)
  const isRecording = ref(false)
  const voiceTranscript = ref('') // 实时识别文本
  const recognition = ref(null)
  const accumulatedText = ref('') // 累积的识别文本

  // 初始化语音识别
  const initVoiceRecognition = () => {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition

    if (!SpeechRecognition) {
      console.warn('当前浏览器不支持语音识别')
      isVoiceSupported.value = false
      return
    }

    isVoiceSupported.value = true
    recognition.value = new SpeechRecognition()

    // 配置语音识别
    recognition.value.lang = lang
    recognition.value.continuous = continuous
    recognition.value.interimResults = true // 显示临时结果
    recognition.value.maxAlternatives = 1

    // 识别结果事件
    recognition.value.onresult = (event) => {
      let fullText = ''
      let hasInterim = false
      let interimText = ''
      
      // 遍历所有结果
      for (let i = 0; i < event.results.length; i++) {
        const result = event.results[i]
        const transcript = result[0].transcript
        
        if (result.isFinal) {
          // 最终结果，添加到累积文本
          fullText += transcript
        } else {
          // 临时结果
          hasInterim = true
          interimText += transcript
        }
      }
      
      // 更新累积文本（只包含最终结果）
      accumulatedText.value = fullText
      
      // 显示文本：最终结果 + 临时结果
      const displayText = hasInterim ? (fullText + interimText) : fullText
      voiceTranscript.value = displayText
      
      // 触发回调
      if (onTranscript) {
        onTranscript(displayText, !hasInterim, fullText)
      }

      // 如果自动停止且有最终结果
      if (autoStop && !hasInterim && fullText.trim()) {
        setTimeout(() => {
          stopRecording()
        }, 500)
      }
    }

    // 识别开始
    recognition.value.onstart = () => {
      console.log('语音识别已开始')
      accumulatedText.value = ''
      voiceTranscript.value = ''
      if (onRecordingStart) onRecordingStart()
    }

    // 识别结束（持续模式下会自动重新启动）
    recognition.value.onend = () => {
      console.log('语音识别已结束')
      
      // 如果是用户主动停止，不重新启动
      if (!isRecording.value) {
        if (onRecordingStop) onRecordingStop()
        return
      }
      
      // 持续模式下，如果还在录音状态，自动重新启动识别
      if (isRecording.value && continuous) {
        try {
          console.log('持续监听模式：自动重新启动识别')
          recognition.value.start()
        } catch (error) {
          // 如果启动失败（可能是因为已经在运行），忽略错误
          if (error.name !== 'InvalidStateError') {
            console.error('重新启动识别失败:', error)
          }
        }
      }
    }

    // 识别错误
    recognition.value.onerror = (event) => {
      console.error('语音识别错误:', event.error)
      isRecording.value = false
      voiceTranscript.value = ''
      if (onRecordingStop) onRecordingStop()

      const errorMessages = {
        'no-speech': '未检测到语音，请重试',
        'audio-capture': '无法访问麦克风，请检查权限',
        'not-allowed': '麦克风权限被拒绝，请在浏览器设置中允许',
        'network': '网络错误，请检查网络连接',
        'aborted': '语音识别已取消'
      }

      const message = errorMessages[event.error] || '语音识别失败，请重试'

      if (event.error !== 'aborted') {
        ElMessage.error(message)
      }
    }
  }

  /**
   * 开始语音录制
   */
  const startRecording = () => {
    if (!recognition.value) {
      ElMessage.warning('语音识别未初始化')
      return
    }

    if (isRecording.value) {
      ElMessage.warning('正在录制中，请稍候')
      return
    }

    try {
      isRecording.value = true
      voiceTranscript.value = ''
      accumulatedText.value = ''
      recognition.value.start()
    } catch (error) {
      console.error('语音识别启动失败:', error)
      ElMessage.error('语音识别启动失败，请稍后重试')
      isRecording.value = false
    }
  }

  /**
   * 停止语音录制
   */
  const stopRecording = () => {
    if (recognition.value && isRecording.value) {
      // 先停止识别
      isRecording.value = false
      
      // 停止识别服务
      try {
        recognition.value.stop()
      } catch (error) {
        console.warn('停止识别时出错:', error)
      }
      
      // 如果有识别文本，触发最终回调
      const finalText = accumulatedText.value.trim() || voiceTranscript.value.trim()
      if (finalText && onTranscript) {
        onTranscript(finalText, true, finalText)
      }
      
      // 清空文本
      voiceTranscript.value = ''
      accumulatedText.value = ''
      
      if (onRecordingStop) onRecordingStop()
    }
  }

  /**
   * 切换录制状态
   */
  const toggleRecording = () => {
    if (!isVoiceSupported.value) {
      ElMessage.warning('您的浏览器不支持语音识别，请使用Chrome或Edge浏览器')
      return
    }

    if (isRecording.value) {
      stopRecording()
    } else {
      startRecording()
    }
  }

  // 组件挂载时初始化
  onMounted(() => {
    initVoiceRecognition()
  })

  // 组件卸载时清理
  onBeforeUnmount(() => {
    if (recognition.value && isRecording.value) {
      recognition.value.stop()
    }
  })

  return {
    isVoiceSupported,
    isRecording,
    voiceTranscript,
    startRecording,
    stopRecording,
    toggleRecording
  }
}
